package cn.com.hp.feature.controller;

import cn.com.hp.feature.domain.entity.SysUserInfo;
import cn.com.hp.feature.response.BaseResponse;
import cn.com.hp.feature.service.ISysUserInfoService;
import cn.com.hp.feature.service.IWechatService;
import cn.com.hp.feature.util.RequestUtils;
import cn.com.hp.feature.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpHeaders;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author: hjz
 * @since: 2022/9/6
 * @description:
 */
@RestController
@AllArgsConstructor
@RequestMapping("/wechat")
@Api(value = "微信小程序相关接口", tags = "微信小程序相关接口")
@Slf4j
public class WechatController {

   @Autowired
   private IWechatService wechatService;

   @Autowired
   private ISysUserInfoService userInfoService;

    @GetMapping("/getOpenId/{code}")
    @ApiOperation(value = "根据微信登陆code获取openid", notes = "传入微信登陆返回的code")
    public BaseResponse getWechatOpenId(@PathVariable String code) {
        BaseResponse response = new BaseResponse();
        String openid = wechatService.getWechatOpenId(code);
        response.setData(openid);
        return response;
    }

    @GetMapping("/login")
    @ApiOperation(value = "根据微信登陆code进行登陆(返回openid)", notes = "传入微信登陆返回的code")
    public BaseResponse loginByWechatCode(@PathVariable String code) {
        BaseResponse response = new BaseResponse();
        String openid = wechatService.getWechatOpenId(code);
        if (ToolUtil.isNotEmpty(openid)){
            SysUserInfo userInfo = userInfoService.getOne(new QueryWrapper<SysUserInfo>().eq("open_id",openid));
            if (userInfo!=null){
                response.setData(userInfo);
            }else {
                //如果库中还没有该用户，则新增一条只有openid的用户记录并返回给前端
                userInfo = new SysUserInfo();
                userInfo.setOpenId(openid);
                userInfoService.save(userInfo);
                response.setData(userInfo);
            }
            return response;
        }
        response.setData(openid);
        return response;
    }
}
